package com.news.model.http;

import com.news.base.BaseConverterFactory;
import com.news.base.HttpResponse;
import com.news.model.bean.Joke;
import com.news.model.http.converter.JokeConverterFactory;
import com.news.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/3/1 0001.
 */

public class RetrofitHelper {

    /**
     * 统一线程处理
     *
     * @param <T>
     * @return
     */
    public <T> Observable.Transformer<T, T> rxSchedulerHelper() {    //compose简化线程
        return new Observable.Transformer<T, T>() {
            @Override
            public Observable<T> call(Observable<T> observable) {
                return observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    private <T> T getService(Class<T> tClass, String baseUrl, BaseConverterFactory factory) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(factory.getClient())
                .addConverterFactory(factory)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(tClass);
    }

    public Observable<HttpResponse<ArrayList<Joke>>> fetchJokeContent(int page, int pageSize, String sort, long time) {
        ApiService service = getService(ApiService.class, ApiService.BASE_URL, JokeConverterFactory.create());
        Map<String, String> params = baseParams();
        params.put("page", String.valueOf(page));
        params.put("pagesize", String.valueOf(pageSize));
        params.put("sort", sort);
        params.put("time", String.valueOf(time / 1000));
        LogUtil.d("RetrofitHelper", "joke: " + params);
        return service.jokeContent(params).compose(this.<HttpResponse<ArrayList<Joke>>>rxSchedulerHelper());
    }

    public Observable<HttpResponse<ArrayList<Joke>>> fetchJokeImage() {
        ApiService service = getService(ApiService.class, ApiService.BASE_URL1, JokeConverterFactory.create());
        Map<String, String> params = baseParams();
        params.put("type", "pic");
        LogUtil.d("RetrofitHelper", "joke: " + params);
        return service.jokeImage(params).compose(this.<HttpResponse<ArrayList<Joke>>>rxSchedulerHelper());
    }

    private Map<String, String> baseParams() {
        HashMap<String, String> params = new HashMap<>();
        params.put("key", "3b2d9e044154d2bf1d847cb8d428a33d");
        return params;

    }
}
